import { type StyleValue } from 'vue'

/**
 * 跟随鼠标在元素中的位置，产生偏移style
 * @param boxRef 依据的box
 * @returns
 */
export function useMoveByMouse(boxRef: Ref<HTMLElement>) {
  const data = reactive({
    left: 0,
    top: 0,
  })

  const { elementX, elementY, elementHeight, elementWidth, isOutside } = useMouseInElement(boxRef)

  onMounted(() => {
    boxRef.value.addEventListener('mousemove', () => {
      if (!isOutside.value) {
        const left = elementX.value / elementWidth.value
        const top = elementY.value / elementHeight.value
        Object.assign(data, { left, top })
      }
    })
  })

  function createStyle(config?: {
    distance?: number // 移动距离
    follow?: boolean // 移动方向
    recoveryTime?: number // 还原时间
  }) {
    const { follow = false, distance = 5, recoveryTime = 0.6 } = config || {}
    let TRANS: Function
    TRANS = follow ? (e: number) => (e * 2 - 1) * distance : (e: number) => (e * -2 + 1) * distance
    return computed<StyleValue>(() => {
      if (isOutside.value)
        return {
          transition: `all ${recoveryTime}s`,
          transform: 'translate(0px,0px)',
          display: 'block',
        }
      const { left, top } = data

      return {
        transform: `translate(${TRANS(left)}px,${TRANS(top)}px)`,
        transition: 'all 0s', // 增加这个时间，动画会变得流畅，但是可能会有性能问题
        display: 'block',
      }
    })
  }
  return { ...toRefs(data), createStyle }
}

// useParallax版本：
// export function useMoveByMouse(boxRef: Ref<HTMLElement>) {
//   const { tilt: left, roll: top, source } = useParallax(boxRef)
//   function createStyle(config?: {
//     distance?: number // 移动距离
//     follow?: boolean // 移动方向
//     recoveryTime?: number // 还原时间
//   }) {
//     const { follow = false, distance = 5, recoveryTime = 0.6 } = config || {}
//     let TRANS: Function
//     TRANS = follow ? (e: number) => e * distance * -1 : (e: number) => e * distance
//     return computed<StyleValue>(() => {
//       return {
//         transform: `translate(${TRANS(left.value)}px,${TRANS(top.value)}px)`,
//         transition: 'all 0.21s',
//         display: 'block',
//       }
//     })
//   }
//   return { left, top, createStyle }
// }
